<?php

namespace app\company\service;

use app\model\AuthRuleModel;
use app\model\platform\PlatformConfigModel;
use app\model\PlatformModel;
use app\model\UserModel;
use think\Service;

class PlatformService extends Service
{
    /**
     * 平台-左侧选项
     */
    public function leftOption($data): array
    {
        $province_ids = [];
        $city_ids = [];
        $area_ids = [];
        $province = [];
        $city = [];
        $area = [];
        $is_ids = [];
        foreach ($data as $item) {
            if ($item['level'] == 1) {
                $is_ids['province_id'][$item['province_id']] = $item;
            }
            if ($item['level'] == 2) {
                $is_ids['city_id'][$item['city_id']] = $item;
            }
            if (!in_array($item['province_id'], $province_ids)) {
                $province_ids[] = $item['province_id'];
                $province[] = [
                    'level' => 1,
                    'name' => $item['province_name'],
                    'areas_id' => $item['province_id'],
                    'num' => $item['num'] ?? 0
                ];
            }
            if (!empty($item['city_id']) && !in_array($item['city_id'], $city_ids)) {
                $city_ids[] = $item['city_id'];
                $city[$item['province_id']][] = [
                    'level' => 2,
                    'name' => $item['city_name'],
                    'areas_id' => $item['city_id'],
                    'num' => $item['num'] ?? 0
                ];
            }
            if (!empty($item['area_id']) && !in_array($item['area_id'], $area_ids)) {
                $area_ids[] = $item['area_id'];
                $area[$item['city_id']][] = [
                    'level' => 3,
                    'name' => $item['area_name'],
                    'areas_id' => $item['area_id'],
                    'id' => $item['id'],
                    'num' => $item['num'] ?? 0
                ];
            }
        }
        $list = [];
        foreach ($province as $item) {
            if (isset($is_ids['province_id'][$item['areas_id']])) {
                $item['id'] = $is_ids['province_id'][$item['areas_id']]['id'];
            } else {
                $item['id'] = 0;
            }
            if (isset($city[$item['areas_id']])) {
                $item['child'] = $city[$item['areas_id']];
                foreach ($item['child'] as &$item2) {
                    if (isset($is_ids['city_id'][$item2['areas_id']])) {
                        $item2['id'] = $is_ids['city_id'][$item2['areas_id']]['id'];
                    } else {
                        $item2['id'] = 0;
                    }
                    if (isset($area[$item2['areas_id']])) {
                        $item2['child'] = $area[$item2['areas_id']];
                    }
                }
            }
            $list[] = $item;
        }
        return $list;
    }

    /**
     * 添加平台
     * @return false|string
     */
    public static function add($param, $userData): bool|string
    {
        $PlatformModel = new PlatformModel();
        $PlatformModel->startTrans();
        try {
            $param['company_id'] = $userData['company_id'];
            $param['time'] = time();
            $is_where = [];
            $is_message = '';
            //判断上级是否添加
            if ($param['level'] == 1) {
                if (empty($param['province_id'])) throw new \Exception('请选择完整区域！');
                $param['areas_id'] = $param['province_id'];
                //省级
                $is_where = [
                    ['company_id', '=', $userData['company_id']],
                    ['province_id', '=', $param['province_id']],
                    ['level', '=', 1]
                ];
                $is_message = '该省级平台已存在';
            } elseif ($param['level'] == 2) {
                if (empty($param['city_id'])) throw new \Exception('请选择完整区域！');
                $param['areas_id'] = $param['city_id'];
                //市级
                $is_where = [
                    ['company_id', '=', $userData['company_id']],
                    ['city_id', '=', $param['city_id']],
                    ['level', '=', 2]
                ];
                $is_message = '该市级平台已存在';
            } elseif ($param['level'] == 3) {
                if (empty($param['area_id'])) throw new \Exception('请选择完整区域！');
                $param['areas_id'] = $param['area_id'];
                //区级
                $is_where = [
                    ['company_id', '=', $userData['company_id']],
                    ['area_id', '=', $param['area_id']],
                    ['level', '=', 3]
                ];
                $is_message = '该区级平台已存在';
            }
            $is = $PlatformModel->where($is_where)->value('id');
            if ($is) throw new \Exception($is_message);
            if (isset($param['user'])) {
                $user = $param['user'];
                unset($param['user']);
            }
            if (empty($param['logo'])) {
                $param['logo'] = env('SETTING.UNIT_ICON');
            }
            if (empty($param['index_logo'])) {
                $param['index_logo'] = env('SETTING.SOFTWARE_LOGO');
            }
            if (empty($param['photo_one'])) {
                $param['photo_one'] = env('SETTING.PHOTO_ONE');
            }
            if (empty($param['photo_one'])) {
                $param['photo_one'] = env('SETTING.PHOTO_TWO');
            }
            if (empty($param['banner'])) {
                $param['banner'] = env('SETTING.PC_BANNER');
            }
            $platform_id = $PlatformModel->insertGetId($param);
            if (!PlatformService::AddDefaultConfig($platform_id)) throw new \Exception('默认配置，设置失败！');
            //添加超管
            if (isset($user) && count($user) > 0) {
                $user_save = [];
                $UserModel = new UserModel();
                foreach ($user as $item) {
                    $user_save[] = [
                        'company_id' => $userData['company_id'],
                        'areas_id' => $param['areas_id'],
                        'platform_id' => $platform_id,
                        'name' => '超级管理员',
                        'type' => 2,
                        'username' => $item['username'],
                        'password' => encrypt_password($item['password']),
                        'avatar' => '/user_avatar/admin.png',
                        'level' => $param['level'],
                        'province_id' => $param['province_id'],
                        'city_id' => $param['city_id'],
                        'area_id' => $param['area_id'],
                        'province_name' => $param['province_name'],
                        'city_name' => $param['city_name'],
                        'area_name' => $param['area_name'],
                        'time' => $item['time']
                    ];
                }
                if (!empty($user_save)) {
                    $usernameData = array_column($user_save, 'username');
                    $uid = $UserModel->where('username', 'in', $usernameData)->value('id');
                    if ($uid) throw new \Exception('账号已存在！');
                    $UserModel->insertAll($user_save);
                }
            }
            $PlatformModel->commit();
            return success(['id' => $platform_id], '添加成功！');
        } catch (\Exception $e) {
            $PlatformModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 编辑平台
     * @return false|string
     */
    public static function update($param, $userData): bool|string
    {
        $PlatformModel = new PlatformModel();
        $PlatformModel->startTrans();
        try {
            $info = $PlatformModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $UserModel = new UserModel();
            if (!empty($param['del'])) {
                $UserModel->where('id', 'in', $param['del'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                unset($param['del']);
            }
            if (!empty($param['user'])) {
                $param['areas_id'] = match ($param['level']) {
                    1 => $param['province_id'],
                    2 => $param['city_id'],
                    3 => $param['area_id'],
                    default => throw new \Exception('参数错误！'),
                };
                $user = $param['user'];
                $user_save = [];
                $ids = $UserModel->where([
                    ['company_id', '=', $userData['company_id']],
                    ['areas_id', '=', $param['areas_id']],
                    ['type', '=', 2]
                ])->column('id');
                foreach ($user as $item) {
                    if (isset($item['id']) && in_array($item['id'], $ids)) {
                        $user_update = [
                            'areas_id' => $param['areas_id'],
                            'level' => $param['level'],
                            'province_id' => $param['province_id'],
                            'city_id' => $param['city_id'],
                            'area_id' => $param['area_id'],
                            'province_name' => $param['province_name'],
                            'city_name' => $param['city_name'],
                            'area_name' => $param['area_name'],
                            'time' => $item['time']
                        ];
                        if (!empty($item['username'])) {
                            $user_update['username'] = $item['username'];
                        }
                        if (!empty($item['password'])) {
                            $user_update['password'] = encrypt_password($item['password']);
                        }
                        $UserModel->where('id', '=', $item['id'])->update($user_update);
                    } else {
                        $user_save[] = [
                            'company_id' => $userData['company_id'],
                            'areas_id' => $param['areas_id'],
                            'platform_id' => $param['id'],
                            'name' => '超级管理员',
                            'type' => 2,
                            'username' => $item['username'],
                            'password' => encrypt_password($item['password']),
                            'level' => $param['level'],
                            'province_id' => $param['province_id'],
                            'city_id' => $param['city_id'],
                            'area_id' => $param['area_id'],
                            'province_name' => $param['province_name'],
                            'city_name' => $param['city_name'],
                            'area_name' => $param['area_name'],
                            'time' => $item['time']
                        ];
                    }
                }
                if (count($user_save) > 0) {
                    $usernameData = array_column($user_save, 'username');
                    $uid = $UserModel->where('username', 'in', $usernameData)->value('id');
                    if ($uid) throw new \Exception('账号已存在！');
                    $UserModel->insertAll($user_save);
                }
                unset($param['user']);
            }
            if (!empty($param['rules'])) {
                $rules = explode(',', $param['rules']);
                $param['rules'] = implode(',', PlatformService::AssignPermissions($rules));
            }
            $info->save($param);
            $PlatformModel->commit();
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $PlatformModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 平台获取上级信息
     * @param int $company_id 公司id
     * @param array $param 省市区id（条件）
     * @return array
     */
    public function platformSuperiorInfo(int $company_id, array $param): array
    {
        $field = 'rules,is_cloud,start_time,end_time,admin_num,consultant_num,user_num,company_num';
        $PlatformModel = new PlatformModel();
        switch ($param['level']) {
            case 2:
                $info = $PlatformModel->where([
                    ['company_id', '=', $company_id],
                    ['level', '=', 1],
                    ['province_id', '=', $param['province_id']]
                ])->field($field)->find();
                break;
            case 3:
                $info = $PlatformModel->where([
                    ['company_id', '=', $company_id],
                    ['level', '=', 2],
                    ['city_id', '=', $param['city_id']]
                ])->field($field)->find();
                break;
        }
        if (!empty($info)){
            return $info->toArray();
        }else{
            return [
                'rules' => '346,347,348,349,350,351,354,355,356,357,360,361,362,363,4,23,51,52,53,54,21,55,56,57,26,58,59,60,35,42,61,62,63,64,65,66,67,68,69,43,70,71,72,73,74,76,79,80,81,82,83,84,85,86,77,87,88,89,90,91,92,93,94,78,95,96,97,98,99,100,101,102,103,104,75,105,106,107,108,109,110,111,120,121,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,157,158,159,160,161,162,165,167,169,171,172,173,175,177,179,182,184,186,188,190,192,194,196,198,201,203,205,207,210,211,213,215,218,220,221,225,226,228,231,233,237,239,240,243,244,246,248,251,253,255,257,259,261,262,264,266,268,270,272,274,276,227,229,245,247,249,250,252,254,256,230,258,294,295,296,260,297,298,299,300,232,263,265,267,269,271,273,275,234,277,279,281,283,285,235,286,287,288,289,290,291,236,238,292,293,241,242,44,47,163,174,176,178,180,181,183,185,187,189,191,193,164,195,197,199,200,202,204,206,208,209,212,214,166,216,217,219,48,168,170,222,224,49,50,14,15,17,19,20,22,24,25,27,28,29,30,18,31,32,33,34,36,37,38,39,40,41,2,3,6,8,9,10,12,13,5,334,335,336,337,338,339,340,341,342,343,344,345,370,371,372,373,374,364,365,366,369',
                'is_cloud' => 0,
                'start_time' => 1745027278,
                'end_time' => 2055909893,
                'admin_num' => 999999999,
                'consultant_num' => 999999999,
                'user_num' => 999999999,
                'company_num' => 999999999,
            ];
        }
    }

    /**
     * 单位获取上级信息
     * @param int $company_id 公司id
     * @param array $param 省市区id（条件）
     * @return array
     */
    public function unitSuperiorInfo(int $company_id, array $param): array
    {
        $field = 'rules,is_cloud,start_time,end_time,admin_num,consultant_num,user_num,company_num';
        $PlatformModel = new PlatformModel();
        switch ($param['level']) {
            case 1:
                $info = $PlatformModel->where([
                    ['company_id', '=', $company_id],
                    ['level', '=', 1],
                    ['province_id', '=', $param['province_id']]
                ])->field($field)->find();
                break;
            case 2:
                $info = $PlatformModel->where([
                    ['company_id', '=', $company_id],
                    ['level', '=', 2],
                    ['city_id', '=', $param['city_id']]
                ])->field($field)->find();
                break;
            case 3:
                $info = $PlatformModel->where([
                    ['company_id', '=', $company_id],
                    ['level', '=', 3],
                    ['area_id', '=', $param['area_id']]
                ])->field($field)->find();
                break;
        }
        if (!empty($info)){
            return $info->toArray();
        }else{
            return [
                'rules' => '346,347,348,349,350,351,354,355,356,357,360,361,362,363,4,23,51,52,53,54,21,55,56,57,26,58,59,60,35,42,61,62,63,64,65,66,67,68,69,43,70,71,72,73,74,76,79,80,81,82,83,84,85,86,77,87,88,89,90,91,92,93,94,78,95,96,97,98,99,100,101,102,103,104,75,105,106,107,108,109,110,111,120,121,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,157,158,159,160,161,162,165,167,169,171,172,173,175,177,179,182,184,186,188,190,192,194,196,198,201,203,205,207,210,211,213,215,218,220,221,225,226,228,231,233,237,239,240,243,244,246,248,251,253,255,257,259,261,262,264,266,268,270,272,274,276,227,229,245,247,249,250,252,254,256,230,258,294,295,296,260,297,298,299,300,232,263,265,267,269,271,273,275,234,277,279,281,283,285,235,286,287,288,289,290,291,236,238,292,293,241,242,44,47,163,174,176,178,180,181,183,185,187,189,191,193,164,195,197,199,200,202,204,206,208,209,212,214,166,216,217,219,48,168,170,222,224,49,50,14,15,17,19,20,22,24,25,27,28,29,30,18,31,32,33,34,36,37,38,39,40,41,2,3,6,8,9,10,12,13,5,334,335,336,337,338,339,340,341,342,343,344,345,370,371,372,373,374,364,365,366,369',
                'is_cloud' => 0,
                'start_time' => 1745027278,
                'end_time' => 2055909893,
                'admin_num' => 999999999,
                'consultant_num' => 999999999,
                'user_num' => 999999999,
                'company_num' => 999999999,
            ];
        }
    }

    /**
     * 分配权限
     * @param $id
     * @return array
     */
    public static function AssignPermissions($id): array
    {
        $AuthRuleModel = new AuthRuleModel();
        $data = $AuthRuleModel->field('id,pid')->where('status', '=', 1)->select();
        $data2 = [];
        foreach ($data as $v) {
            $data2[$v['id']] = $v['pid'];
        }
        $ids = [];
        foreach ($id as $v) {
            if (empty($data2[$v])) {
                $ids[] = $v;
                continue;
            }
            if ($data2[$v] > 0) {
                PlatformService::getJuniorPermissions($data, $v, $ids);
            }
            $ids[] = $v;
        }
        return $ids;
    }

    /**
     * 获取下级权限
     * @param $data
     * @param $id
     * @param $ids
     * @return void
     */
    public static function getJuniorPermissions($data, $id, &$ids): void
    {
        $categories = getAllSubcategories($data, $id);
        $ids = array_merge($ids, array_column($categories, 'id'));
    }

    /**
     * 添加平台默认配置
     * @param $platform_id
     * @return int
     */
    public static function AddDefaultConfig($platform_id): int
    {
        $time = time();
        $data = [
            [
                'platform_id' => $platform_id,
                'key' => 'software_settings',
                'value' => '{"news_center":"1","news_type":["1","2","3","4","5","6"],"data_board":"1","enter_board":["1"],"board_verfied":"1","home_todo":["1","2","3","4"],"web_url":"1","screen_protect":"1","is_mobile":"1"}',
                'explain' => '软件设置',
                'time' => $time
            ], [
                'platform_id' => $platform_id,
                'key' => 'landscape_settings',
                'value' => '[{"id":"25","dot":"1","x":"40","y":"105"},{"id":"26","dot":"1","x":"560","y":"105"},{"id":"27","dot":"1","x":"967","y":"105"},{"id":"28","dot":"1","x":"1380","y":"105"},{"id":"29","dot":"1","x":"40","y":"530"},{"id":"30","dot":"1","x":"560","y":"565"},{"id":"31","dot":"1","x":"1380","y":"460"},{"id":"35","dot":"1","x":"560","y":"320"}]',
                'explain' => '数据大屏设置',
                'time' => $time
            ],
        ];
        $PlatformConfigModel = new PlatformConfigModel();
        return $PlatformConfigModel->insertAll($data);
    }
}